<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\admin\model\Admin as AdminModel;
use app\admin\model\scanwork\Order;
use app\admin\model\scanwork\Allocation;
use app\admin\model\scanwork\Report;
use app\admin\model\scanwork\Config as ConfigModel;
use app\admin\model\scanwork\Product;
use app\admin\model\scanwork\ProductModel;
use app\admin\model\scanwork\Process;
use think\Db;
use think\Exception;

/**
 * 千牛小程序后端管理员API控制器（管理端）
 */
class QianniuAdmin extends Api
{
    protected $noNeedLogin = ['adminLogin', 'checkAdminToken', 'getOrders', 'getAllocations', 'getReports', 'auditReport', 'getReportDetail', 'getProducts', 'getProcesses', 'getUsers', 'createAllocation', 'batchCreateAllocation', 'getModels', 'getOrderModels', 'getOrderDetail', 'createOrder', 'updateOrder', 'deleteOrder', 'uploadAuditImage', 'getActiveReports', 'getActiveReportDetail', 'auditActiveReport', 'getAllocationDetail', 'getOverviewStats', 'getReportStats', 'getUserActivity', 'getProductStats', 'getProcessStats'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        
        // 支持Bearer token格式
        $authorization = $this->request->header('Authorization');
        if ($authorization && strpos($authorization, 'Bearer ') === 0) {
            $token = substr($authorization, 7);
            $this->request->server(['HTTP_TOKEN' => $token]);
        }
        
        // 检查是否为管理员登录的方法
        $action = $this->request->action();
        $adminMethods = ['getOrders', 'getAllocations', 'getReports', 'auditReport', 'getReportDetail', 'getProducts', 'getProcesses', 'getUsers', 'createAllocation', 'batchCreateAllocation', 'uploadAuditImage', 'getActiveReports', 'getActiveReportDetail', 'auditActiveReport', 'getAllocationDetail', 'getOverviewStats', 'getReportStats', 'getUserActivity', 'getProductStats', 'getProcessStats'];
        
        if (in_array($action, $adminMethods)) {
            // 验证管理员登录
            $adminInfo = session('qianniu_admin_info');
            $adminToken = session('qianniu_admin_token');
            
            if (!$adminInfo || !$adminToken) {
                $this->error('请先登录', null, 401);
            }
        }
    }

    /**
     * 管理员登录
     */
    public function adminLogin()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        
        if (!$username || !$password) {
            $this->error('用户名和密码不能为空');
        }
        
        // 查找管理员用户
        $admin = AdminModel::where('username', $username)->find();
        if (!$admin) {
            $this->error('用户不存在');
        }
        
        // 验证密码
        if ($admin->password !== md5($password)) {
            $this->error('密码错误');
        }
        
        // 检查用户状态
        if ($admin->status !== 'normal') {
            $this->error('用户已被禁用');
        }
        
        // 生成token
        $token = md5($admin->id . time() . rand(1000, 9999));
        
        // 保存管理员信息到session
        $sessionData = [
            'admin_id' => $admin->id,
            'username' => $admin->username,
            'nickname' => $admin->nickname,
            'role' => $admin->role
        ];
        session('qianniu_admin_info', $sessionData);
        session('qianniu_admin_token', $token);
        
        // 同时保存到数据库
        $admin->qianniu_token = $token;
        $admin->qianniu_token_expire = time() + 7200; // 2小时过期
        $admin->save();
        
        $this->success('登录成功', [
            'token' => $token,
            'admin_info' => [
                'id' => $admin->id,
                'username' => $admin->username,
                'nickname' => $admin->nickname,
                'role' => $admin->role,
                'is_admin' => true
            ]
        ]);
    }

    /**
     * 验证管理员token
     */
    public function checkAdminToken()
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }

        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        $admin = AdminModel::where('qianniu_token', $token)
                          ->where('qianniu_token_expire', '>', time())
                          ->find();
        
        if (!$admin) {
            $this->error('token无效或已过期');
        }

        $this->success('token有效', [
            'admin_info' => [
                'id' => $admin->id,
                'username' => $admin->username,
                'nickname' => $admin->nickname,
                'role' => $admin->role,
                'is_admin' => true
            ]
        ]);
    }

    /**
     * 获取订单列表
     */
    public function getOrders()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        $list = Order::with(['orderModels.model.product'])
            ->where($where)
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page]);
        
        $this->success('获取成功', [
            'list' => $list->items(),
            'total' => $list->total(),
            'page' => $page,
            'limit' => $limit
        ]);
    }

    /**
     * 获取订单详情
     */
    public function getOrderDetail()
    {
        $orderId = $this->request->get('order_id');
        if (!$orderId) {
            $this->error('参数错误');
        }
        
        $order = Order::with(['orderModels.model.product'])
            ->find($orderId);
        
        if (!$order) {
            $this->error('订单不存在');
        }
        
        $this->success('获取成功', $order);
    }

    /**
     * 创建订单
     */
    public function createOrder()
    {
        $orderNo = $this->request->post('order_no');
        $productId = $this->request->post('product_id');
        $quantity = $this->request->post('quantity');
        $remark = $this->request->post('remark', '');
        
        if (!$orderNo || !$productId || !$quantity) {
            $this->error('必填字段不能为空');
        }
        
        // 检查订单号是否已存在
        $exists = Order::where('order_no', $orderNo)->find();
        if ($exists) {
            $this->error('订单号已存在');
        }
        
        Db::startTrans();
        try {
            $orderData = [
                'order_no' => $orderNo,
                'product_id' => $productId,
                'quantity' => $quantity,
                'remark' => $remark,
                'status' => 0,
                'createtime' => time()
            ];
            
            $order = Order::create($orderData);
            
            Db::commit();
            $this->success('创建成功', $order);
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('创建失败：' . $e->getMessage());
        }
    }

    /**
     * 更新订单
     */
    public function updateOrder()
    {
        $orderId = $this->request->post('order_id');
        $orderNo = $this->request->post('order_no');
        $productId = $this->request->post('product_id');
        $quantity = $this->request->post('quantity');
        $remark = $this->request->post('remark', '');
        
        if (!$orderId) {
            $this->error('订单ID不能为空');
        }
        
        $order = Order::get($orderId);
        if (!$order) {
            $this->error('订单不存在');
        }
        
        $order->order_no = $orderNo;
        $order->product_id = $productId;
        $order->quantity = $quantity;
        $order->remark = $remark;
        $order->save();
        
        $this->success('更新成功');
    }

    /**
     * 删除订单
     */
    public function deleteOrder()
    {
        $orderId = $this->request->post('order_id');
        
        if (!$orderId) {
            $this->error('订单ID不能为空');
        }
        
        $order = Order::get($orderId);
        if (!$order) {
            $this->error('订单不存在');
        }
        
        $order->delete();
        $this->success('删除成功');
    }

    /**
     * 获取分工列表
     */
    public function getAllocations()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        $list = Allocation::with(['order', 'model.product', 'process', 'user'])
            ->where($where)
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page]);
        
        $this->success('获取成功', [
            'list' => $list->items(),
            'total' => $list->total()
        ]);
    }

    /**
     * 获取分工详情
     */
    public function getAllocationDetail()
    {
        $allocationId = $this->request->get('allocation_id');
        
        if (!$allocationId) {
            $this->error('参数错误');
        }
        
        $allocation = Allocation::with(['order', 'model.product', 'process', 'user'])
            ->find($allocationId);
        
        if (!$allocation) {
            $this->error('分工记录不存在');
        }
        
        $this->success('获取成功', $allocation);
    }

    /**
     * 创建分工任务
     */
    public function createAllocation()
    {
        $orderId = $this->request->post('order_id');
        $modelId = $this->request->post('model_id');
        $processId = $this->request->post('process_id');
        $userId = $this->request->post('user_id');
        $quantity = $this->request->post('quantity');
        $workType = $this->request->post('work_type', 'piece');
        
        if (!$orderId || !$modelId || !$processId || !$userId || !$quantity) {
            $this->error('参数不完整');
        }
        
        Db::startTrans();
        try {
            $data = [
                'order_id' => $orderId,
                'model_id' => $modelId,
                'process_id' => $processId,
                'user_id' => $userId,
                'quantity' => $quantity,
                'work_type' => $workType,
                'status' => 0,
                'createtime' => time()
            ];
            
            $allocation = Allocation::create($data);
            
            Db::commit();
            $this->success('分工任务创建成功', $allocation);
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('创建失败：' . $e->getMessage());
        }
    }

    /**
     * 批量创建分工任务
     */
    public function batchCreateAllocation()
    {
        $orderId = $this->request->post('order_id');
        $allocations = $this->request->post('allocations/a', []);
        
        if (!$orderId || empty($allocations)) {
            $this->error('参数不完整');
        }
        
        Db::startTrans();
        try {
            foreach ($allocations as $allocationData) {
                $data = [
                    'order_id' => $orderId,
                    'model_id' => $allocationData['model_id'],
                    'process_id' => $allocationData['process_id'],
                    'user_id' => $allocationData['user_id'],
                    'quantity' => $allocationData['quantity'],
                    'work_type' => $allocationData['work_type'] ?? 'piece',
                    'status' => 0,
                    'createtime' => time()
                ];
                
                Allocation::create($data);
            }
            
            Db::commit();
            $this->success('批量创建成功');
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('创建失败：' . $e->getMessage());
        }
    }

    /**
     * 获取报工列表
     */
    public function getReports()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        $list = Report::with(['user', 'allocation.order', 'allocation.model.product', 'allocation.process'])
            ->where($where)
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page]);
        
        $items = $list->items();
        foreach ($items as &$item) {
            $item['statusText'] = $this->getReportStatusText($item['status']);
        }
        
        $this->success('获取成功', [
            'list' => $items,
            'total' => $list->total()
        ]);
    }

    /**
     * 获取报工详情
     */
    public function getReportDetail()
    {
        $reportId = $this->request->get('report_id');
        
        if (!$reportId) {
            $this->error('参数错误');
        }
        
        $report = Report::with(['user', 'allocation.order', 'allocation.model.product', 'allocation.process'])
            ->find($reportId);
        
        if (!$report) {
            $this->error('报工记录不存在');
        }
        
        $report['statusText'] = $this->getReportStatusText($report['status']);
        
        $this->success('获取成功', $report);
    }

    /**
     * 审核报工
     */
    public function auditReport()
    {
        $reportId = $this->request->post('report_id');
        $status = $this->request->post('status');
        $auditReason = $this->request->post('audit_reason', '');
        
        if (!$reportId || !in_array($status, ['1', '2'])) {
            $this->error('参数错误');
        }
        
        $report = Report::get($reportId);
        if (!$report) {
            $this->error('报工记录不存在');
        }
        
        Db::startTrans();
        try {
            $report->status = $status;
            if ($status == '2') {
                $report->audit_reason = $auditReason;
            }
            
            $adminInfo = session('qianniu_admin_info');
            $report->audit_user_id = $adminInfo['admin_id'] ?? 1;
            $report->audit_time = time();
            
            $report->save();
            
            Db::commit();
            $this->success('审核成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('审核失败：' . $e->getMessage());
        }
    }

    /**
     * 获取主动报工列表
     */
    public function getActiveReports()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('page_size', 20);
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($status !== '') {
            $where[] = ['status', '=', intval($status)];
        }
        
        $list = Report::with(['user', 'allocation.order', 'allocation.model.product', 'allocation.process'])
            ->where($where)
            ->order('id desc')
            ->paginate($pageSize, false, ['page' => $page]);
        
        $items = $list->items();
        foreach ($items as &$item) {
            $item['statusText'] = $this->getReportStatusText($item['status']);
        }
        
        $this->success('获取成功', [
            'list' => $items,
            'total' => $list->total()
        ]);
    }

    /**
     * 获取主动报工详情
     */
    public function getActiveReportDetail()
    {
        $id = $this->request->get('id');
        
        if (!$id) {
            $this->error('参数错误');
        }
        
        $report = Report::with(['user', 'allocation.order', 'allocation.model.product', 'allocation.process'])
            ->where('id', $id)
            ->find();
        
        if (!$report) {
            $this->error('报工记录不存在');
        }
        
        $report['statusText'] = $this->getReportStatusText($report['status']);
        
        $this->success('获取成功', $report);
    }

    /**
     * 审核主动报工
     */
    public function auditActiveReport()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        $remark = $this->request->post('remark', '');
        
        if (!$id || !in_array($status, [1, 2])) {
            $this->error('参数错误');
        }
        
        $report = Report::get($id);
        if (!$report) {
            $this->error('报工记录不存在');
        }
        
        if ($report['status'] != 0) {
            $this->error('该报工记录已审核');
        }
        
        Db::startTrans();
        try {
            $report->status = $status;
            $report->audit_reason = $remark;
            
            $adminInfo = session('qianniu_admin_info');
            $report->audit_user_id = $adminInfo['admin_id'] ?? 1;
            $report->audit_time = time();
            
            $report->save();
            
            Db::commit();
            $this->success('审核成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('审核失败：' . $e->getMessage());
        }
    }

    /**
     * 获取产品列表
     */
    public function getProducts()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('page_size', 20);
        $keyword = $this->request->get('keyword', '');
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($keyword) {
            $where[] = ['name|code', 'like', '%' . $keyword . '%'];
        }
        if ($status !== '') {
            $where[] = ['status', '=', intval($status)];
        }
        
        $list = Product::where($where)
            ->order('id desc')
            ->paginate($pageSize, false, ['page' => $page]);
        
        $items = $list->items();
        foreach ($items as &$item) {
            $item['modelCount'] = ProductModel::where('product_id', $item['id'])->count();
            $item['orderCount'] = Order::where('product_id', $item['id'])->count();
        }
        
        $this->success('获取成功', [
            'list' => $items,
            'total' => $list->total()
        ]);
    }

    /**
     * 获取型号列表
     */
    public function getModels()
    {
        $productId = $this->request->get('product_id');
        
        $where = [];
        if ($productId) {
            $where[] = ['product_id', '=', $productId];
        }
        
        $list = ProductModel::with(['product'])
            ->where($where)
            ->order('id desc')
            ->select();
        
        $this->success('获取成功', $list);
    }

    /**
     * 获取订单型号列表
     */
    public function getOrderModels()
    {
        $orderId = $this->request->get('order_id');
        
        if (!$orderId) {
            $this->error('参数错误');
        }
        
        $list = \app\admin\model\scanwork\OrderModel::with(['model.product'])
            ->where('order_id', $orderId)
            ->order('id desc')
            ->select();
        
        $this->success('获取成功', $list);
    }

    /**
     * 获取工序列表
     */
    public function getProcesses()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('page_size', 20);
        $keyword = $this->request->get('keyword', '');
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($keyword) {
            $where[] = ['name|code', 'like', '%' . $keyword . '%'];
        }
        if ($status !== '') {
            $where[] = ['status', '=', intval($status)];
        }
        
        $list = Process::where($where)
            ->order('id desc')
            ->paginate($pageSize, false, ['page' => $page]);
        
        $items = $list->items();
        foreach ($items as &$item) {
            $item['allocationCount'] = Allocation::where('process_id', $item['id'])->count();
            $item['completedCount'] = Report::where('allocation.process_id', $item['id'])->where('status', 1)->count();
            $avgHours = Report::where('allocation.process_id', $item['id'])->where('status', 1)->avg('work_hours');
            $item['avgHours'] = round($avgHours, 2);
        }
        
        $this->success('获取成功', [
            'list' => $items,
            'total' => $list->total()
        ]);
    }

    /**
     * 获取用户列表
     */
    public function getUsers()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('page_size', 20);
        $keyword = $this->request->get('keyword', '');
        $role = $this->request->get('role', '');
        
        $where = [];
        if ($keyword) {
            $where[] = ['nickname|username', 'like', '%' . $keyword . '%'];
        }
        if ($role) {
            $where[] = ['role', '=', $role];
        }
        
        $list = User::where($where)
            ->field('id,nickname,username,avatar,employee_no,qianniu_user_id,role,status,department,createtime')
            ->order('id desc')
            ->paginate($pageSize, false, ['page' => $page]);
        
        $this->success('获取成功', [
            'list' => $list->items(),
            'total' => $list->total()
        ]);
    }

    /**
     * 上传审核图片
     */
    public function uploadAuditImage()
    {
        $file = $this->request->file('image');
        
        if (!$file) {
            $this->error('没有接收到文件');
        }
        
        $info = $file->validate(['size' => 10240 * 1024, 'ext' => 'jpg,jpeg,png,gif'])
            ->move('uploads/qianniu/audit/');
            
        if (!$info) {
            $this->error('图片上传失败：' . $file->getError());
        }
        
        $filename = $info->getSaveName();
        $url = ConfigModel::getSiteDomain() . '/uploads/qianniu/audit/' . $filename;
        
        $this->success('上传成功', ['url' => $url]);
    }

    /**
     * 获取概览统计
     */
    public function getOverviewStats()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $where = $this->getTimeWhere($timeRange);
        
        $totalOrders = Order::where($where)->count();
        $totalUsers = User::where('status', 'normal')->count();
        $totalReports = Report::where($where)->count();
        $totalWage = Report::where($where)->sum('wage');
        
        $this->success('获取成功', [
            'totalOrders' => $totalOrders,
            'totalUsers' => $totalUsers,
            'totalReports' => $totalReports,
            'totalWage' => round($totalWage, 2)
        ]);
    }

    /**
     * 获取报工统计
     */
    public function getReportStats()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $where = $this->getTimeWhere($timeRange);
        
        $pending = Report::where($where)->where('status', 0)->count();
        $approved = Report::where($where)->where('status', 1)->count();
        $rejected = Report::where($where)->where('status', 2)->count();
        $avgHours = Report::where($where)->where('status', 1)->avg('work_hours');
        
        $this->success('获取成功', [
            'pending' => $pending,
            'approved' => $approved,
            'rejected' => $rejected,
            'avgHours' => round($avgHours, 2)
        ]);
    }

    /**
     * 获取用户活跃度
     */
    public function getUserActivity()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $limit = $this->request->get('limit', 10);
        $where = $this->getTimeWhere($timeRange);
        
        $list = Report::with(['user'])
            ->where($where)
            ->where('status', 1)
            ->group('user_id')
            ->field('user_id, COUNT(*) as reportCount, SUM(work_hours) as totalHours, SUM(wage) as totalWage')
            ->order('reportCount desc')
            ->limit($limit)
            ->select();
        
        foreach ($list as &$item) {
            $item['user_id'] = $item['user_id'];
            $item['reportCount'] = intval($item['reportCount']);
            $item['totalHours'] = round($item['totalHours'], 2);
            $item['totalWage'] = round($item['totalWage'], 2);
        }
        
        $this->success('获取成功', $list);
    }

    /**
     * 获取产品统计
     */
    public function getProductStats()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $where = $this->getTimeWhere($timeRange);
        
        $list = Report::with(['allocation.model.product'])
            ->where($where)
            ->group('allocation.model_id')
            ->field('allocation.model_id, COUNT(*) as reportCount')
            ->select();
        
        foreach ($list as &$item) {
            $modelId = $item['allocation']['model_id'];
            $orderCount = Order::where($where)->where('model_id', $modelId)->count();
            $completionRate = $orderCount > 0 ? round(($item['reportCount'] / $orderCount) * 100, 2) : 0;
            
            $item['product_name'] = $item['allocation']['model']['product']['name'] ?? '未知产品';
            $item['model_name'] = $item['allocation']['model']['name'] ?? '未知型号';
            $item['orderCount'] = $orderCount;
            $item['completionRate'] = $completionRate;
        }
        
        $this->success('获取成功', $list);
    }

    /**
     * 获取工序统计
     */
    public function getProcessStats()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $where = $this->getTimeWhere($timeRange);
        
        $list = Report::with(['allocation.process'])
            ->where($where)
            ->group('allocation.process_id')
            ->field('allocation.process_id, COUNT(*) as completedCount, AVG(work_hours) as avgHours')
            ->select();
        
        foreach ($list as &$item) {
            $processId = $item['allocation']['process_id'];
            $allocationCount = Allocation::where($where)->where('process_id', $processId)->count();
            
            $item['process_name'] = $item['allocation']['process']['name'] ?? '未知工序';
            $item['description'] = $item['allocation']['process']['description'] ?? '';
            $item['allocationCount'] = $allocationCount;
            $item['avgHours'] = round($item['avgHours'], 2);
        }
        
        $this->success('获取成功', $list);
    }

    /**
     * 获取时间条件
     */
    private function getTimeWhere($timeRange)
    {
        $now = time();
        $where = [];
        
        switch ($timeRange) {
            case 'today':
                $startTime = strtotime(date('Y-m-d 00:00:00'));
                $where[] = ['createtime', '>=', $startTime];
                break;
            case 'week':
                $startTime = strtotime('monday this week');
                $where[] = ['createtime', '>=', $startTime];
                break;
            case 'month':
                $startTime = strtotime(date('Y-m-01 00:00:00'));
                $where[] = ['createtime', '>=', $startTime];
                break;
            case 'year':
                $startTime = strtotime(date('Y-01-01 00:00:00'));
                $where[] = ['createtime', '>=', $startTime];
                break;
        }
        
        return $where;
    }

    /**
     * 获取报工状态文本
     */
    private function getReportStatusText($status)
    {
        $statusMap = [
            0 => '待审核',
            1 => '已通过',
            2 => '已拒绝'
        ];
        return $statusMap[$status] ?? '未知';
    }
}
